<template>
  <div id="actor-add">
    <el-button style="line-height:25px;"
               @click="$router.go(-1)"
               icon="el-icon-back"
               type="text">返回</el-button>

    <h3>演职员新增/编辑</h3>
    <el-form label-width="120px"
             style="overflow: hidden;">
      <el-form-item label="类型"
                    class="form-item">
        <el-radio-group v-model="addObj.actorType"
                        @change="handleRadioChange">
          <el-radio :label="1">演职员</el-radio>
          <el-radio :label="2">演出团体</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="addObj.actorType===1?'姓名':'名称'"
                    class="form-item">
        <el-input v-model="addObj.name"></el-input>
      </el-form-item>
      <span v-if="addObj.actorType===2">
        <el-form-item label="团体类型"
                      class="form-item">
          <el-select v-model="addObj.typeCode"
                     @change="handleTypeChange"
                     filterable
                     allow-create
                     default-first-option
                     style="width:100%">
            <el-option v-for="(item) in actorGroupTypeList"
                       :key="item.value"
                       :value="item.value"
                       :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="建成年份"
                      class="form-item">
          <el-date-picker v-model="addObj.birthday"
                          type="month"
                          value-format="yyyy-MM-dd"
                          style="width:100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="简介"
                      style="width:100%"
                      class="form-item">
          <el-input type="textarea"
                    :autosize="{ minRows: 3, maxRows: 5 }"
                    v-model="addObj.introduction"></el-input>
        </el-form-item>
      </span>
      <span v-if="addObj.actorType===1">
        <el-form-item label="性别"
                      class="form-item">
          <el-radio-group v-model="addObj.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生年月"
                      class="form-item">
          <el-date-picker v-model="addObj.birthday"
                          type="month"
                          value-format="yyyy-MM-dd"
                          style="width:100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="演职员类型"
                      class="form-item">
          <el-select v-model="addObj.typeCode"
                     @change="handleTypeChange"
                     filterable
                     allow-create
                     default-first-option
                     style="width:100%">
            <el-option v-for="(item) in actorTypeList"
                       :key="item.value"
                       :value="item.value"
                       :label="item.label" />
            <!-- <el-option label="演职员"
                     value="1"></el-option>
          <el-option label="总导演"
                     value="2"></el-option>
          <el-option label="总策划"
                     value="3"></el-option>
          <el-option label="团体"
                     value="4"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="毕业院校"
                      class="form-item">
          <el-input v-model="addObj.shool"></el-input>
        </el-form-item>

        <!-- <el-form-item label="单位类型"
                      class="form-item">
          <el-select v-model="addObj.unitType"
                     filterable
                     default-first-option
                     style="width:100%">
            <el-option label="中央直属院团"
                       value="中央直属院团"></el-option>
            <el-option label="省、市院团"
                       value="省、市院团"></el-option>
            <el-option label="其他"
                       value="其他"></el-option>
            <el-option label="自由职业"
                       value="自由职业"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="单位名称"
                      class="form-item">
          <el-input v-model="addObj.unit"></el-input>
        </el-form-item>
        <el-form-item label="职务"
                      class="form-item">
          <el-input v-model="addObj.job"></el-input>
        </el-form-item>
        <el-form-item label="职称"
                      class="form-item">
          <el-input v-model="addObj.position"></el-input>
        </el-form-item>
        <el-form-item label="政治面貌"
                      class="form-item">
          <!-- <el-input v-model="addObj.politicalStatus"></el-input> -->
          <el-select v-model="addObj.politicalStatus"
                     style="width:100%">
            <el-option label="中共党员"
                       value="中共党员"></el-option>
            <el-option label="共青团员"
                       value="共青团员"></el-option>
            <el-option label="民主党派人士"
                       value="民主党派人士"></el-option>
            <el-option label="群众"
                       value="群众"></el-option>
          </el-select>
        </el-form-item>
      </span>

      <el-form-item label="获奖情况"
                    style="width:100%"
                    class="form-item">
        <el-select v-model="addObj.honors"
                   multiple
                   filterable
                   allow-create
                   default-first-option
                   style="width:100%">
          <el-option value="文华奖"
                     label="文华奖"></el-option>
          <el-option value="中宣部“五个一”工程奖"
                     label="中宣部“五个一”工程奖"></el-option>
          <el-option value="中国戏剧梅花奖"
                     label="中国戏剧梅花奖"></el-option>
          <el-option value="中国舞蹈荷花奖"
                     label="中国舞蹈荷花奖"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item class="form-item especially-item"
                    style="width:100%"
                    label="曾参与演出">
        <el-select v-model="addObj.attendedInfos"
                   multiple
                   filterable
                   style="width:100%">
          <el-option v-for="item in playList"
                     :key="item.playId"
                     :label="item.playName"
                     :value="item.playId" />
          <!-- <el-option label="演出1"
                     value="1"></el-option>
          <el-option label="演出2"
                     value="2"></el-option>
          <el-option label="演出3"
                     value="3"></el-option>
          <el-option label="演出4"
                     value="4"></el-option> -->
        </el-select>
      </el-form-item>

      <el-form-item class="form-item"
                      style="width:100%"
                      label="备注">
          <el-input type="textarea"
                    :autosize="{ minRows: 3, maxRows: 5 }"
                    v-model="addObj.note"></el-input>
      </el-form-item>

      <span v-if="addObj.actorType===1">
        <el-form-item class="form-item"
                      style="width:100%"
                      label="代表作品">
          <el-input type="textarea"
                    :autosize="{ minRows: 3, maxRows: 5 }"
                    v-model="addObj.representative"></el-input>
        </el-form-item>
        <el-form-item class="form-item"
                      style="width:100%"
                      label="简介">
          <el-input type="textarea"
                    :autosize="{ minRows: 3, maxRows: 5 }"
                    v-model="addObj.introduction"></el-input>
        </el-form-item>
        <!-- <el-form-item class="form-item"
                      style="width:100%"
                      label="备注">
          <el-input type="textarea"
                    :autosize="{ minRows: 3, maxRows: 5 }"
                    v-model="addObj.note"></el-input>
        </el-form-item> -->
        <el-form-item label="照片"
                      class="form-item"
                      style="width:100%">
          <div>
            <el-upload action="https://jsonplaceholder.typicode.com/posts/"
                       list-type="picture-card"
                       :limit="1"
                       :http-request="beginUpload"
                       :on-preview="handlePictureCardPreview"
                       :file-list="fileList"
                       :before-upload="beforeAvatarUpload"
                       :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
      </span>

    </el-form>
    <footer style="text-align:center;padding-bottom:25px">
      <el-button type="primary"
                 :loading="btnLoading"
                 @click="submit"
                 size="medium">保存并返回</el-button>
    </footer>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%"
           :src="dialogImageUrl"
           alt="">
    </el-dialog>
  </div>
</template>

<script>
import API from '../../api/actor'
import axios from 'axios'
import actorGroupType from '../../types/actorGroupType'

export default {
  name: 'ActorAdd',
  data() {
    return {
      actorGroupTypeList: actorGroupType.type,
      id: '',
      btnLoading: false,
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      addObj: {
        typeCode: null,
        type: '',
        birthday: null,
        name: '',
        sex: 1,
        shool: '',
        job: '',
        position: '',
        unitType: '',
        unit: '',
        politicalStatus: '',
        attendedInfos: [],
        representative: '',
        honors: [],
        introduction: '',
        originalPhotoName: '',
        photoName: '',
        actorType: 1
      },
      playList: [],
      actorTypeList: []
    }
  },
  mounted() {
    this.getActorType()
    this.getPlayList()
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.queryById(this.$route.query.id)
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type.includes('image');
      if (!isJPG) {
        this.$message.error('上传文件只能是图片格式!');
        return false
      }
      const isSise = new Promise((resolve, reject) => {
        const isLt2M = file.size / 1024 / 1024 < 5;
        const width = 500;
        const height = 300;
        const url = window.URL || window.webkitURL;
        const img = new Image();
        img.onload = () => {
          file.width = img.width;      // 获取到width放在了file属性上
          file.height = img.height;    // 获取到height放在了file属性上
          const valid = isLt2M && img.width >= width && img.height >= height;
          valid ? resolve({ width: img.width, height: img.height }) : reject({ width: img.width, height: img.height });
        };
        img.src = url.createObjectURL(file)
      }).then(() => {
        return file
      }).catch((err) => {
        console.warn(err)
        this.$message.error('图片大小不能超过 5M，图片像素不能低于500*300！');
        return Promise.reject(false)
      })
      console.log(121313, isSise)
      if (!isSise) {
        this.$message.error('图片大小不能超过 5M，图片像素不能低于500*300！');
      }
      return isJPG && isSise
    },
    handleTypeChange(v) {
      switch (this.addObj.actorType) {
        case 1: {
          const arr = this.actorTypeList.filter(a => a.value === v)
          console.log(arr)
          if (arr.length > 0) {
            this.addObj.type = arr[0].label
          } else {
            this.addObj.type = v
          }
          break;
        }
        case 2: {
          this.addObj.type = actorGroupType.formatType(v)
          break;
        }
        default: break;
      }
    },
    guid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0
        const v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16);
      });
    },
    handleRemove(file, fileList) {
      this.addObj.photoName = null
      this.addObj.originalPhotoName = null
      // console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    submit() {
      this.btnLoading = true
      const params = { ...this.addObj }
      params.attendedInfos = this.addObj.attendedInfos.map(a => this.playList.filter(p => p.playId === a)[0])
      if (params.type === params.typeCode) params.typeCode = null
      if (!this.id) {
        API.addActor(params).then(res => {
          this.btnLoading = false
          this.$router.go(-1)
        }).catch(() => {
          this.btnLoading = false
          // this.$router.go(-1)
        })
      } else {
        API.editActor(params).then(res => {
          this.btnLoading = false
          this.$router.go(-1)
        }).catch(() => {
          this.btnLoading = false
        })
      }
    },
    queryById(id) {
      API.getActorById(id).then(res => {
        if (!res.data.typeCode) res.data.typeCode = res.data.type
        res.data.attendedInfos = res.data.attendedInfos && res.data.attendedInfos.map(a => a.playId) || []
        if (res.data.photoUrl) this.fileList.push({ name: '', url: res.data.photoUrl })
        this.addObj = Object.assign({}, this.addObj, res.data)
      })
    },
    getActorType() {
      API.getActorType().then(res => {
        this.actorTypeList = res.data
      })
    },
    getPlayList() {
      API.getPlays().then(res => {
        this.playList = res.data.items
      })
    },
    beginUpload(file) {
      console.log(file)
      this.addObj.originalPhotoName = file.file.name
      const form = new FormData()
      form.append('file', file.file)
      axios.post(process.env.VUE_APP_BASE_API + '/admin/uploadimg', form).then(res => {
        this.addObj.photoName = res.data.data.imgName
      }).catch(err => {
        console.log(err)
        this.addObj.photoName = null
        this.addObj.originalPhotoName = null
      })
    },
    handleRadioChange(v) {
      this.addObj.type = ''
      this.addObj.typeCode = null
    }
  }
}
</script>

<style lang="scss" scoped>
#actor-add {
  width: 800px;
  padding: 0 30px;
  form {
    overflow: hidden;
  }
  .form-item {
    // width: 49%;
    width: 50%;
    float: left;
  }
  /deep/ .item-special {
    label {
      line-height: 1;
    }
  }
  .especially-item /deep/ label {
    // line-height: 1;
  }
}
</style>
